import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

// 导入登陆注册组件
// import Reg from '@/views/Reg/Reg.vue'
// import Login from '@/views/Login/Login.vue'
// import Main from '@/views/Main/Main.vue'
// import Home from '@/views/Menus/Home/Home.vue'
// import UserInfo from '@/views/Menus/User/UserInfo.vue'
// import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
// import UserPwd from '@/views/Menus/User/UserPwd.vue'
// import Article from '@/views/Menus/Article/Article.vue'
// import ArtList from '@/views/Menus/Article/ArtList.vue'

// ★路由懒加载, 比如在 调用Reg时, 会返回一个import('路径'), 实现了仅在需要时,才加载对应的组件页面,
// ★提高了首次打开页面的速度 ,app.js会拆分成以下 若干个js和css文件
// 如果使用了babel,需要在babel.config.js 中配置一个plugins
const Reg = () => import('@/views/Reg/Reg.vue')
const Login = () => import('@/views/Login/Login.vue')
const Main = () => import('@/views/Main/Main.vue')
const Home = () => import('@/views/Menus/Home/Home.vue')
const UserInfo = () => import('@/views/Menus/User/UserInfo.vue')
const UserAvatar = () => import('@/views/Menus/User/UserAvatar.vue')
const UserPwd = () => import('@/views/Menus/User/UserPwd.vue')
const Article = () => import('@/views/Menus/Article/Article.vue')
const ArtList = () => import('@/views/Menus/Article/ArtList.vue')

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 声明路由规则
const routes = [
  {
    path: '/reg',
    component: Reg
  }, {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'user-info',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        component: UserAvatar
      },
      {
        path: 'user-pwd',
        component: UserPwd
      },
      {
        path: 'art-cate',
        component: Article
      },
      {
        path: 'art-list',
        component: ArtList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 注册全局前置守卫
// 传入回调函数
// 参数1: to
// 参数2: from
// 参数3: next() 是否放行
router.beforeEach((to, from, next) => {
  // console.log(store.state.user.token)
  // 需求: 如果 没有token(没有登录) 并且要去的页面既不是login页 也不是 reg页 就自动跳到login页
  if (!store.state.user.token && to.path !== '/login' && to.path !== '/reg') {
    // 提醒用户
    Vue.prototype.$message.error('请先登录再访问!')
    return next('/login')
  }
  next()
})

export default router
